package com.adonis.ejoy.Log;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.adonis.ejoy.MainActivity;
import com.adonis.ejoy.R;
import com.adonis.ejoy.utils.HttpUtil;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;


public class Login extends Activity implements SensorEventListener {   //登录界面活动

    private String baseURL;
    private EditText mAccount;                        //用户名编辑
    private EditText mPwd;                            //密码编辑
    private Button mRegisterButton;                   //注册按钮
    private Button mLoginButton;                      //登录按钮
    private CheckBox mRememberCheck;

    private SharedPreferences login_sp;
    private SharedPreferences.Editor editor;
    private String userName,userPwd;

    private TextView mChangepwdText;
    private UserDataManager mUserDataManager;         //用户数据管理类

    //定义传感器管理
    SensorManager sensorManager;
    //定义布局管理器
    RelativeLayout relativeLayout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        baseURL = getBaseContext().getString(R.string.baseURL);
        //通过id找到相应的控件
        mAccount = (EditText) findViewById(R.id.login_edit_account);
        mPwd = (EditText) findViewById(R.id.login_edit_pwd);
        mRegisterButton = (Button) findViewById(R.id.login_btn_register);
        mLoginButton = (Button) findViewById(R.id.login_btn_login);
//        mCancleButton = (Button) findViewById(R.id.login_btn_cancle);


        mChangepwdText = (TextView) findViewById(R.id.login_text_change_pwd);

        mRememberCheck = (CheckBox) findViewById(R.id.Login_Remember);

        login_sp = getSharedPreferences("userInfo", 0);
        String name=login_sp.getString("USER_NAME", "");
        String pwd =login_sp.getString("PASSWORD", "");
        boolean choseRemember =login_sp.getBoolean("mRememberCheck", false);
        boolean choseAutoLogin =login_sp.getBoolean("mAutologinCheck", false);
        //如果上次选了记住密码，那进入登录页面也自动勾选记住密码，并填上用户名和密码
        if(choseRemember){
            mAccount.setText(name);
            mPwd.setText(pwd);
            mRememberCheck.setChecked(true);
        }

        mRegisterButton.setOnClickListener(mListener);          //采用OnClickListener方法设置不同按钮按下之后的监听事件
        mLoginButton.setOnClickListener(mListener);
//        mCancleButton.setOnClickListener(mListener);
        mChangepwdText.setOnClickListener(mListener);


        ImageView image = (ImageView) findViewById(R.id.logo);             //使用ImageView显示logo
        image.setImageResource(R.drawable.logo);

        if (mUserDataManager == null) {
            mUserDataManager = new UserDataManager(this);
            mUserDataManager.openDataBase();                              //建立本地数据库
        }

        //获取传感器服务
        sensorManager= (SensorManager) getSystemService(SENSOR_SERVICE);
        //获取布局管理器
        relativeLayout= (RelativeLayout) findViewById(R.id.login);
    }

    OnClickListener mListener = new OnClickListener() {                  //不同按钮按下的监听事件选择
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.login_btn_login:                              //登录按钮
                    login();
                    break;
                case R.id.login_btn_register:                            //注册按钮
                    Intent intent_Login_to_Register = new Intent(Login.this,Register.class) ;    //切换Login Activity至RegisterActivity
                    startActivity(intent_Login_to_Register);
                    finish();
                    break;
                /*case R.id.login_btn_cancle:                             //注销按钮
                    cancel();
                    break;*/
                case R.id.login_text_change_pwd:                       //登录界面的注销按钮
                    Intent intent_Login_to_reset = new Intent(Login.this,Resetpwd.class) ;    //切换Login Activity至User Activity
                    startActivity(intent_Login_to_reset);
                    finish();
                    break;
            }
        }
    };

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    Toast.makeText(getBaseContext(), "登录失败,用户名或密码错误",Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    editor.putString("USER_NAME", userName);
                    editor.putString("PASSWORD", userPwd);
                    //是否记住密码
                    if(mRememberCheck.isChecked()){
                        editor.putBoolean("mRememberCheck", true);
                    }else{
                        editor.putBoolean("mRememberCheck", false);
                    }
                    editor.commit();
                    Toast.makeText(getBaseContext(), "登录成功",Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(Login.this, MainActivity.class) ;         //切换Login Activity至User Activity
                    intent.putExtra("uid",msg.sendingUid);
                    Log.d("uid", msg.sendingUid+"");
                    startActivity(intent);
                    finish();
                    break;
            }
        }
    };

    public void login() {                                              //登录按钮监听事件
        if (isUserNameAndPwdValid()) {
            userName = mAccount.getText().toString().trim();    //获取当前输入的用户名和密码信息
            userPwd = mPwd.getText().toString().trim();
            editor =login_sp.edit();
            String url = baseURL + "mvc/login";
            RequestBody body = new FormBody.Builder()
                    .add("name",userName)
                    .add("passwd",userPwd)
                    .build();
            HttpUtil.sendPostRequest(url, body, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String result = response.body().string();
                    Message message = new Message();
                    if("0".equals(result)){
                        message.what = 0;
                    }else {
                        message.what = 1;
                        message.sendingUid = Integer.valueOf(result);
                    }
                    handler.sendMessage(message);
                }
            });
            /*int result=mUserDataManager.findUserByNameAndPwd(userName, userPwd);
            if(result==1){                                             //返回1说明用户名和密码均 正确
                //保存用户名和密码
                editor.putString("USER_NAME", userName);
                editor.putString("PASSWORD", userPwd);

                //是否记住密码
                if(mRememberCheck.isChecked()){
                    editor.putBoolean("mRememberCheck", true);
                }else{
                    editor.putBoolean("mRememberCheck", false);
                }
                editor.commit();

                Intent intent = new Intent(Login.this, MainActivity.class) ;         //切换Login Activity至User Activity
                startActivity(intent);
                finish();
                Toast.makeText(this, getString(R.string.login_success),Toast.LENGTH_SHORT).show();      //登录成功提示
            }else if(result==0){
                Toast.makeText(this, getString(R.string.login_fail),Toast.LENGTH_SHORT).show();         //登录失败提示
            }*/
        }
    }

    /*public void cancel() {           //注销
        if (isUserNameAndPwdValid()) {
            String userName = mAccount.getText().toString().trim();    //获取当前输入的用户名和密码信息
            String userPwd = mPwd.getText().toString().trim();
            int result=mUserDataManager.findUserByNameAndPwd(userName, userPwd);
            if(result==1){                                             //返回1说明用户名和密码均正确
                Toast.makeText(this, getString(R.string.cancel_success),Toast.LENGTH_SHORT).show();//<span style="font-family: Arial;">//注销成功提示</span>
                mPwd.setText("");
                mAccount.setText("");
                mUserDataManager.deleteUserDatabyname(userName);
            }else if(result==0){
                Toast.makeText(this, getString(R.string.cancel_fail),Toast.LENGTH_SHORT).show();  //注销失败提示
            }
        }
    }*/

    public boolean isUserNameAndPwdValid() {                        //判断用户名和密码是否合法
        if (mAccount.getText().toString().trim().equals("")) {
            Toast.makeText(this, getString(R.string.account_empty),
                    Toast.LENGTH_SHORT).show();
            return false;
        } else if (mPwd.getText().toString().trim().equals("")) {
            Toast.makeText(this, getString(R.string.pwd_empty),
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    @Override
    protected void onResume() {
        if (mUserDataManager == null) {
            mUserDataManager = new UserDataManager(this);
            mUserDataManager.openDataBase();
        }
        super.onResume();
        sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT),sensorManager.SENSOR_DELAY_GAME);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        if (mUserDataManager != null) {
            mUserDataManager.closeDataBase();
            mUserDataManager = null;
        }
        super.onPause();
    }

    //监听传感器值的变化
    @Override
    public void onSensorChanged(SensorEvent event) {
        //获取传感器的值
        float[] values=event.values;
        //获取传感器类型
        int sensorType=event.sensor.getType();
        switch (sensorType){
            case Sensor.TYPE_LIGHT:
                //获取窗口管理属性
                WindowManager.LayoutParams lp=this.getWindow().getAttributes();
                //LayoutParams相当于一个Layout的信息包，封装了Layout的位置/宽/高等
                //计算屏幕亮度(通过光照传感器的值设置屏幕亮度的值)
                lp.screenBrightness=Float.valueOf(values[0])*(1f/255f);
                //设置屏幕亮度
                //        this.getWindow().setAttributes(lp);
                if (values[0]<=20){               //如果光照值为20
                    //更换成夜晚背景图片
                    relativeLayout.setBackgroundResource(R.drawable.night);
                }
                else{
                    //更换成夜晚白天图片
                    relativeLayout.setBackgroundResource(R.drawable.day);
                }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}
